﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace FuturamaPDA {
    public partial class ListScreen : Form {
		private Logger logger;
		private TagReader reader;
		private XmlTextReader xmlReader;

		private string userId, name, listId;
		private HomeScreen parent;

		delegate void TagFoundDelegate(string tag);
		private System.Object lockThis;

        public ListScreen(HomeScreen parent, string userId, string name, string listId) {
			this.userId = userId;
			this.name = name;
			this.listId = listId;
			this.parent = parent;
			this.lockThis = new System.Object();

			Connector con = new Connector();
			con.Add("command", "getGroceryList");
			con.Add("id", this.userId);
			string xmlResponse = con.GetResponse();

			this.xmlReader = new XmlTextReader(new StringReader(xmlResponse));
			this.xmlReader.WhitespaceHandling = WhitespaceHandling.None;

			InitializeComponent();
			
			this.logger = Logger.Instance;
			this.reader = TagReader.Instance;
			this.reader.RfidScanned += new EventHandler<ReadEventArgs>(reader_RfidScanned);
			this.reader.ReaderError += new EventHandler<ReaderErrorEventArgs>(reader_ReaderError);
			this.reader.startReading();
        }

		private void reader_ReaderError(object sender, ReaderErrorEventArgs e) {
			MessageBox.Show(e.ErrorMessage);
		}

		private void reader_RfidScanned(object sender, ReadEventArgs e) {
			TagFoundDelegate tfd = new TagFoundDelegate(tagFound);
			this.Invoke(tfd, e.Rfid);
		}

		private void tagFound(string tag) {
			lock (lockThis) {
				DataRow[] foundRows = this.table.Select(String.Format("Rfid = '{0}'", tag));
				if (foundRows.Length > 0) {
					foundRows[0][1] = "---";
					this.table.AcceptChanges();
					this.grid.Update();
				} else {
					Connector tor = new Connector();
					tor.Add("command", "getProductsByTags");
					tor.Add("id", tag);

					string newProductXml = tor.GetResponse();

					XmlTextReader newProductReader = new XmlTextReader(new StringReader(newProductXml));
					newProductReader.WhitespaceHandling = WhitespaceHandling.None;

					if (newProductReader.MoveToContent() == XmlNodeType.Element && newProductReader.Name == "products") {
						if (newProductReader.Read() && newProductReader.Name == "product") {
							newProductReader.Read();
							string productId = newProductReader.ReadElementContentAsString();
							string productName = newProductReader.ReadElementContentAsString();
							string productPrice = newProductReader.ReadElementContentAsString();
							newProductReader.Read();
							string productTagId = newProductReader.ReadElementContentAsString();
							string productTag = newProductReader.ReadElementContentAsString();

							this.table.Rows.Add(productTag, "---", productName, productPrice);
							this.table.AcceptChanges();
							this.grid.Update();
						} else {
							MessageBox.Show("Deze tag staat niet geregistreerd als product");
						}
					} else {
						MessageBox.Show("Er is iets misgegaan met het verbinden.");
					}
				}
			}
		}

		private void route_Click(object sender, System.EventArgs e) {
			MessageBox.Show("Deze functie is nog niet geimplementeerd.");
		}
		
		private void deals_Click(object sender, System.EventArgs e) {
			MessageBox.Show("Deze functie is nog niet geimplementeerd.");
		}
		
		private void addProduct_Click(object sender, System.EventArgs e) {
			MessageBox.Show("Deze functie is nog niet geimplementeerd.");
		}

		private void settings_Click(object sender, System.EventArgs e) {
			MessageBox.Show("Deze functie is nog niet geimplementeerd.");
		}

		private void logOff_Click(object sender, System.EventArgs e) {
			this.parent.addHandlers();
			this.parent.Show();
			this.parent.Activate();
			this.Close();
		}

		private void getRows(XmlTextReader rowReader) {
			if (rowReader.MoveToContent() == XmlNodeType.Element && rowReader.Name == "grocerylist" && rowReader.Read()) {
				string listId = rowReader.ReadElementContentAsString();
				string listName = rowReader.ReadElementContentAsString();

				while (rowReader.Read()) {
					if (rowReader.NodeType.Equals(XmlNodeType.Element) && rowReader.LocalName == "product") {
						rowReader.Read();
						string productId = rowReader.ReadElementContentAsString();
						string productName = rowReader.ReadElementContentAsString();
						string productPrice = rowReader.ReadElementContentAsString();
						string productAmount = rowReader.ReadElementContentAsString();
						string productTag = rowReader.ReadElementContentAsString();

						this.table.Rows.Add(productTag, productAmount, productName, productPrice);
					}
				}
			} else {
				MessageBox.Show("Er is iets fout gegaan met het verbinden probeer het later opnieuw.");
			}
			rowReader.Close();
		}

		public void startReading() {
			this.reader.startReading();
		}
    }
}